<template>
  <div class="carousel-container">
    <div
      class="carousel-inner"
      :class="durationClass"
      :style="{ transform: `translateX(-${nowIndex.value * 100}%)` }"
    >
      <slot></slot>
      <div v-if="lastPage">{{ lastPage }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, useSlots, useTemplateRef } from 'vue'

const slots = useSlots()
const nowIndex = ref(0)
const durationClass = useTemplateRef('carousel-transition')
let lastPage = null

onMounted(() => {
  const carouselItems = slots.default()[0].children || []
  lastPage = carouselItems[0]

  setInterval(() => {
    nowIndex.value++
    if (nowIndex.value === carouselItems.length) {
      setTimeout(() => {
        durationClass.value = ''
      }, 500)
      setTimeout(() => {
        nowIndex.value = 0
      }, 1000)
      setTimeout(() => {
        durationClass.value = 'carousel-transition'
      }, 1500)
    }
  }, 2000)
})
</script>

<style scoped>
.carousel-container {
  width: 100vw;
  overflow-x: hidden;
}

.carousel-inner {
  display: flex;
  transition: transform 0.3s ease-in-out;
}

.carousel-transition {
  transition: transform 0.3s ease-in-out;
}
</style>
